const { Friend } = require('../../../model/friend');
const { Message } = require('../../../model/message')
// 引入分页模块
// const pagination = require('mongoose-sex-page')
const { decodeToken } = require('../../../middleGuard/jwt')
const { userProps } = require('../../../populate')

module.exports = async (req, res) => {
  // const { index, size } = req.query
  // const query = {}
  const user = decodeToken(req.headers.authorization).userId
  // const list = await pagination(Goods).find(query).sort({_id: -1}).page(index).size(size).populate('category').populate('user').exec()
  // 查找我的好友列表
  const list = await Friend.find({ user }).sort({ _id: -1 }).populate('friend', userProps).populate('user', userProps)
  // 未读消息数量
  const unreadMsgNum = await Message.count({ toUser: user, isRead: false })
  console.log('unreadMsgNum', unreadMsgNum)
  const receiveList = []
  const sendList = []
  let flag = 0
  if (list.length > 0) {
    list.forEach(async (item, i) => {
      // console.log(item)
      // 朋友发给我的消息
      const receiveMsg = await Message.findOne({ fromUser: item.friend._id, toUser: user }).sort({_id: -1})
      // 我发给朋友的消息
      const sendMsg = await Message.findOne({ fromUser: user, toUser: item.friend._id }).sort({_id: -1})
      if(receiveMsg) {
        console.log(i)
        receiveList.push({ friend: item.friend, content: receiveMsg.content, createTime: receiveMsg.createTime, unreadMsgNum: await Message.count({ fromUser: item.friend._id ,toUser: user, isRead: false }) })
      }
      if(sendMsg) {
        sendList.push({ friend: item.friend, content: sendMsg.content, createTime: sendMsg.createTime, unreadMsgNum: 0 })
      }
      flag++
      if (flag >= list.length) {
        const sortList = [...receiveList, ...sendList].sort((next, pre) => pre.createTime - next.createTime)
        const filterRepetitions = []
        sortList.forEach(item => {
          if(!filterRepetitions.some(fs => fs.friend._id == item.friend._id)) {
            filterRepetitions.push(item)
          }
        })
        res.json({
          data: filterRepetitions,
          receiveList,
          sendList
        })
      }
    })
  } else {
    res.json({
      data: [],
      message: '没有好友'
    })
  }
}